# coding: utf-8
from me.api_utils import *
from me.api_utils import WXAppAPIView as APIView
from .model_serializers import *
from me.qcloudstorage import cos
from me.file_utils import *
from PIL import Image
from me.settings import IMG_HOST
import uuid


class AlbumAPIView(APIView):
    model = Album

    def get(self, request, id):
        """
        获取相册详情
        :param id: 相册ID
        """
        album = self.check_obj_and_owner_permission(request, Album, id)
        return success_resp(AlbumSerializers(instance=album).data)

    def post(self, request):
        """
        相册创建
        """
        user = request.user
        album = Album.objects.create(user=user)
        return success_resp(AlbumSerializers(album).data)

    def put(self, request):
        """
        更新同步相册
        """
        album_id = request.data.get('id')
        album = self.check_obj_and_owner_permission(request, Album, album_id)
        form = AlbumSerializers(instance=album, data=request.data)
        valid_and_exception(form, 2000)
        form.save()
        return success_resp(AlbumSerializers(album).data)

    def delete(self, request, id):
        """
        删除相册
        """
        album = self.check_obj_and_owner_permission(request, Album, id)
        album.delete()
        return success_resp()


class AlbumListOwnersAPIView(APIView):

    def get(self, request):
        """
        获取自己的相册列表
        """
        albums = Album.objects.filter(user=request.user).prefetch_related("user").order_by('-update_time')
        return success_resp(AlbumSerializers(instance=albums, many=True).data)


class AlbumResourceAPIView(APIView):

    def post(self, request, id):
        self.check_obj_and_owner_permission(request, model=Album, id=id)
        file_obj = request.FILES['image']
        file_path = 'user/%s/%s%s' % (request.user.id, uuid.uuid1().hex, file_extension(file_obj.__str__()))
        res = cos.upload_file(file_obj, file_path)
        img = Image.open(file_obj)
        width, height = img.size
        if res['code'] == 0:
            return success_resp({
                'type': 'image',
                'width': width,
                'source': 'qcloud',
                'height': height,
                'url': '%s/%s' % (IMG_HOST, file_path)
            })
        else:
            return error_resp(2003)

